﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
//using www.SService;
using www.Controllerss;
using www.Core.Contract.DataContract;

namespace www.Admin
{
    public partial class BrowerConfideAdmin : System.Web.UI.Page
    {
        #region Value

        private readonly ObjectCache _cache = MemoryCache.Default;
        //private readonly HyServicesClient _service = new HyServicesClient();
        private readonly LanguageController _languageController=new LanguageController();
        private readonly StaffController _staffController=new StaffController();
        private readonly LoginController _loginController=new LoginController();
        private readonly MenuMemberController _menuMemberController=new MenuMemberController();
        private readonly MenuController _menuController=new MenuController();
        private readonly CategoryController _categoryController=new CategoryController();
        private readonly StoryController _storyController=new StoryController();
        static long _id = 0;
        private static int iLanguageCode;

        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToInt32(Session["role"]) != 1 && Convert.ToInt32(Session["role"]) != 2)
            {
                Message("Bạn không đủ quyền để thực hiện chức năng này.");
                Response.Redirect("Default.aspx");
            }
            if (Cache["Language"] == null)
            {
                var lLanguage = _languageController.GetLanguageDataContracts();
                if (lLanguage.Any())
                    Cache.Insert("Language", lLanguage.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }
            if (_cache["Employee"] == null)
            {
                var lData = _staffController.GetStaffDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Employee", lData.ToList(), policy);
                }
            }
            if (_cache["UserClient"] == null)
            {
                var lData = _loginController.GetAllClientUser();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("UserClient", lData.ToList(), policy);
                }
            }
            if (!IsPostBack)
            {
                var lLanguages = (List<RelaxLanguageDataContract>)Cache["Language"];
                if (lLanguages != null)
                {
                    var lReturn = lLanguages.Where(l => l.Type == 1);
                    Addlist(lReturn);
                }
                LoadStaff();
                //LoadCategory();
                LoadData();
            }
        }
        #endregion

        #region Event
        protected void ddlgroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void ddlStaff_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCategory();
        }
        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }
        protected void lbtdel2_Click(object sender, EventArgs e)
        {
            try
            {
                DeleteLanguage(iLanguageCode);
            }
            catch (Exception)
            {

            }

        }
        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_PostConfide.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var il = e.CommandArgument.ToString().Split('_');
                if (il.Length <= 1)
                    return;
                _id = Convert.ToInt32(il[0]);
                iLanguageCode = Convert.ToInt32(il[1]);
                var lData = (List<RelaxStoryDataContract>)_cache["News"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == iLanguageCode);
                if (first == null)
                    return;
                if (e.CommandName == "cmd_Detail")
                {
                    txtname.Value = first.Name;
                    txtdecription.Value = first.Decription;
                    txtKeyword.Value = first.Keyword;
                    txtord.Value = first.Priority.ToString();
                    chkactive.Checked = first.Active == 1;
                    ddlCategory.Value = first.CategoryId.ToString();
                    txtDetail.Value = HttpUtility.HtmlDecode(first.Detail);

                    pncontrols.Visible = true;
                    pnviews.Visible = false;
                }
                else if (e.CommandName == "cmd_delete")
                {

                    DeleteLanguage(iLanguageCode);
                    Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                    lData.Remove(first);
                    _cache["News"] = lData;
                    LoadData();
                    Message("Xóa Thành Công");
                    _id = 0;

                }
            }
            catch (Exception)
            {

            }
        }

        protected void grid_PostConfide_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var userId = ((Label)e.Row.FindControl("lblUserId")).Text;
                if (!string.IsNullOrEmpty(userId))
                {
                    var userName = (Label)e.Row.FindControl("lblUserName");
                    var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
                    if (lData != null)
                    {
                        var first = lData.FirstOrDefault(p => p.Id == Convert.ToInt32(userId));
                        if (first != null)
                        {
                            userName.Text = first.UserName;
                        }
                    }
                }
            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        #endregion

        #region Business
        private void LoadStaffMenu()
        {
            if (_cache["StaffMenu"] == null)
            {
                var lData = _menuMemberController.GetMenuMemberDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("StaffMenu", lData.ToList(), policy);
                }
            }
            if (_cache["Menu"] == null)
            {
                var lData = _menuController.GetMenuDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Menu", lData.ToList(), policy);
                }
            }
            if (_cache["Category"] == null)
            {
                var lData = _categoryController.GetCategoryDataContracts();
                var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                _cache.Set("Category", lData.ToList(), policy);
            }
        }
        private void LoadCategory()
        {
            LoadStaffMenu();
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lCategory = (List<RelaxCategoryDataContract>)_cache["Category"];
            if (lMenu == null)
                return;
            if (lMenuStaff == null)
                return;
            if (lCategory == null)
                return;
            var lReturn = (from c in lCategory.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display)
                           join m in lMenu.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display) on c.Id equals m.CategoryId
                           join s in lMenuStaff.Where(p => p.MemberId == Convert.ToInt32(Session["StaffId"]) && p.Active == Constant.Active.Display) on m.Id equals
                    s.MenuId
                           select new { c.Id, c.Name, c.Type }).ToList();
            var tmp = lReturn.ToList();
            foreach (var item in tmp)
            {
                var checkItem = lReturn.Where(p => p.Id == item.Id).ToList();
                if (checkItem.Count > 1)
                {
                    var first = checkItem.FirstOrDefault();
                    foreach (var item1 in checkItem)
                    {
                        lReturn.Remove(item1);
                    }
                    lReturn.Add(first);
                }
            }
            ddlCategory1.Items.Add(new ListItem("---Chọn---", "0"));
            ddlCategory.Items.Add(new ListItem("---Chọn---", "0"));
            var lParent = lReturn.Where(p => p.Type == 0).ToList();
            if (lParent.Any())
            {
                foreach (var item in lParent)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    ddlCategory.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    var lreturn1 = lCategory.Where(p => p.Type == item.Id && p.Languagecode == 1).ToList();
                    if (lreturn1.Any())
                    {
                        foreach (var item1 in lreturn1)
                        {
                            ddlCategory1.Items.Add(new ListItem("--" + item1.Name, item1.Id.ToString()));
                            ddlCategory.Items.Add(new ListItem("--" + item1.Name, item1.Id.ToString()));
                        }
                    }
                }
            }
            else
            {
                foreach (var item in lReturn)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    ddlCategory.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
            }

        }
        private void LoadStaff()
        {
            var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
            ddlStaff.Items.Clear();
            ddlStaff.Items.Add(new ListItem("---Chọn---", "0"));
            if (lData != null)
            {
                foreach (var item in lData)
                {
                    ddlStaff.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
            }
        }
        private void Addlist(IEnumerable<RelaxLanguageDataContract> lLanguageDataContracts)
        {
            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Add(new ListItem("---Chọn---", "0"));
            foreach (var item in lLanguageDataContracts)
            {
                var items = new ListItem(item.Name, item.Id.ToString());
                ddlLanguage.Items.Add(items);
            }
        }
        private void Save()
        {
            try
            {
                if (string.IsNullOrEmpty(txtname.Value) ||
                    string.IsNullOrEmpty(txtord.Value) || string.IsNullOrEmpty(ddlCategory.Value) || string.IsNullOrEmpty(txtdecription.Value) || string.IsNullOrEmpty(txtDetail.Value) || string.IsNullOrEmpty(txtKeyword.Value))
                {
                    Message("Bạn phải nhập đầy đủ thông tin gợi ý trên");
                    return;
                }
                if (Convert.ToInt32(ddlCategory.Value) <= 0)
                {
                    Message("Bạn phải chọn Danh mục.");
                    return;
                }
                var lData = (List<RelaxStoryDataContract>)_cache["News"];

                var ac = chkactive.Checked ? 1 : 0;
                var path = "Images/News/";
                var postedfile = fuUpload.PostedFile;
                if (postedfile != null)
                {
                    var filename = postedfile.FileName;
                    var lUpdate = new List<RelaxStoryDataContract>();
                    if (lData == null)
                        return;
                    var first =
                        lData.FirstOrDefault(
                            p => p.Id == _id && p.Languagecode == 1);
                    if (first == null)
                        return;
                    var img = first.Image;
                    if (string.IsNullOrEmpty(filename))
                        path = first.Image;
                    else
                        path += filename;

                    var advertise = new RelaxStoryDataContract
                    {
                        Id = _id,
                        Active = ac,
                        Priority = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                        Keyword = txtKeyword.Value,
                        Name = txtname.Value,
                        Tag = txtname.Value.Replace(' ', '-'),
                        Decription = txtdecription.Value,
                        Languagecode = iLanguageCode,
                        Detail = HttpUtility.HtmlEncode(txtDetail.Value),
                        IsDefault = 0,
                        Image = path,
                        CategoryId = Convert.ToInt32(ddlCategory.Value),
                        Userid = first.Userid,
                        UserBrower = first.UserBrower,
                        Date = first.Date,
                        Report = first.Report,
                        View = first.View
                    };
                    lUpdate.Add(advertise);

                    if (_storyController.Update(lUpdate))
                    {
                        if (!string.IsNullOrEmpty(filename))
                        {
                            Utilities.DeleteFile(Server.MapPath("~/" + img));
                            postedfile.SaveAs(Server.MapPath("~/" + path));
                        }

                        foreach (var item in lUpdate)
                        {
                            var firstordefault =
                                lData.FirstOrDefault(p => p.Id == item.Id && p.Languagecode == item.Languagecode);
                            if (firstordefault != null)
                            {
                                firstordefault.Name = item.Name;
                                firstordefault.Tag = item.Tag;
                                firstordefault.Priority = lUpdate[0].Priority;
                                firstordefault.Keyword = item.Keyword;
                                firstordefault.Decription = item.Decription;
                                firstordefault.Active = lUpdate[0].Active;
                                firstordefault.Image = lUpdate[0].Image;
                                firstordefault.Detail = item.Detail;
                                firstordefault.Userid = lUpdate[0].Userid;
                                firstordefault.IsDefault = lUpdate[0].IsDefault;
                                firstordefault.CategoryId = lUpdate[0].CategoryId;
                                firstordefault.View = lUpdate[0].View;
                                firstordefault.Report = item.Report;
                                firstordefault.UserBrower = lUpdate[0].UserBrower;
                            }
                            else
                            {
                                item.Priority = lUpdate[0].Priority;
                                item.Active = lUpdate[0].Active;
                                item.Image = lUpdate[0].Image;
                                item.UserBrower = lUpdate[0].UserBrower;
                                item.Userid = lUpdate[0].Userid;
                                item.View = lUpdate[0].View;
                                item.IsDefault = lUpdate[0].IsDefault;
                                item.CategoryId = lUpdate[0].CategoryId;
                                lData.Add(item);
                            }
                        }
                        _cache["News"] = lData;
                        Message("Sửa Thành Công !");
                        _id = 0;
                        pncontrols.Visible = false;
                        pnviews.Visible = true;
                        LoadData();
                    }
                }
                else
                {
                    Message("Bạn phải chọn ảnh !");
                }
            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnviews.Visible = true;
            pncontrols.Visible = false;
            _id = 0;
            LoadData();
        }
        private void DeleteLanguage(int iLanguagecode)
        {
            if (iLanguagecode <= 0) return;

            if (_id > 0)
            {
                _storyController.Delete(new List<long> { _id }, iLanguagecode);
            }

        }
        private void Delete()
        {
            try
            {
                if (grid_PostConfide.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_PostConfide.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_PostConfide.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_PostConfide.Rows[i].FindControl("lblId")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                if (_storyController.Delete(lAd, Convert.ToInt32(ddlLanguage.SelectedValue)))
                {
                    var lData = (List<RelaxStoryDataContract>)_cache["News"];
                    if ((lData.Any()))
                    {
                        foreach (var id in lAd)
                        {
                            var first = lData.FirstOrDefault(p => p.Id == id && p.Languagecode == Convert.ToInt32(ddlLanguage.SelectedValue));
                            if (first != null)
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                                lData.Remove(first);
                            }
                            hang++;
                        }
                    }
                    if (hang != 0)
                    {
                        Message("Có " + hang + "bản ghi được Xóa Thành Công");
                    }
                    else
                    {
                        Message("Không có bản ghi nào được xóa !");
                    }
                    _cache["News"] = lData;
                    LoadData();
                }

            }
            catch { }
        }
       
        public void LoadData()
        {
            grid_PostConfide.DataSourceID = null;
            if (_cache["News"] == null)
            {
                var lData = _storyController.GetStoryDataContract();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("News", lData.ToList(), policy);
                }
            }
            long userId = 0;

            var lUser = (List<RelaxLoginsDataContract>)_cache["UserClient"];
            if (lUser != null)
            {
                var relaxLoginsDataContract = lUser.FirstOrDefault(p => p.StaffId == Convert.ToInt32(ddlStaff.SelectedValue));
                if (relaxLoginsDataContract != null)
                    userId = relaxLoginsDataContract.Id;
            }
            var lData1 = (List<RelaxStoryDataContract>)_cache["News"];
            if (lData1 != null)
            {
                var lReturn = (from c in lData1.Where(p => p.Languagecode == Convert.ToInt32(ddlLanguage.SelectedValue) && p.UserBrower == userId && p.CategoryId == Convert.ToInt32(string.IsNullOrEmpty(ddlCategory1.SelectedValue) ? "0" : ddlCategory1.SelectedValue))
                               select new { c.Active, c.Decription, c.Id, c.Keyword, c.Languagecode, c.Name, c.Priority, c.Tag, c.Image, c.Date, c.UserBrower }).Distinct().OrderByDescending(o => o.Id);
                grid_PostConfide.DataSource = lReturn.ToList();
            }
            grid_PostConfide.DataBind();
        }

        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion
    }
}